#include "gamestatemanager.h"

GameStateManager::GameStateManager()
{
    _isRunning = true;

    GameInfo* gameInfo = new GameInfo();
    //gameInfo->setWhite(HUMAN);
    //gameInfo->setBlack(HUMAN);

    _stateMap[GST_GAME] = new Game(*this, *gameInfo);
    _stateMap[GST_PROMOTION] = new Promotion(*gameInfo);
    _stateMap[GST_MENU] = new Menu(*this, *gameInfo);
    _stateMap[GST_CONFIRMQUIT] = new ConfirmQuit(*gameInfo);

    pushState(GST_MENU);
    //pushState(GST_CONFIRMQUIT);
    //pushState(GST_GAME);
    //pushState(GST_PROMOTION);
}

GameStateManager::~GameStateManager()
{
    delete _stateMap[GST_GAME];
}

void GameStateManager::update(float dt, const Input& input)
{
    if (!_stateStack.empty()) {

        // Ugly hack since we cannot use iterators here
        int index = _stateStack.size() - 1;

        if (!_stateStack[index]->update(dt, input)) {

            std::vector<IGameState*>::iterator itr = _stateStack.begin();
            for (int i = 0; i < index; ++i, ++itr) { }
            _stateStack.erase(itr);
        }
    }

    _isRunning = glfwGetWindowParam(GLFW_OPENED);
}

void GameStateManager::draw()
{
    for (std::vector<IGameState*>::iterator i = _stateStack.begin();
            i != _stateStack.end(); ++i) {
        if (*i == _stateStack.front()) {
            (*i)->getView().draw(true);
        } else {
            (*i)->getView().draw(false);
        }
    }

}

void GameStateManager::pushState(GameStateType state)
{
    IGameState* newState = _stateMap[state];
    newState->onEnter();
    newState->getView().onEnter();

    _stateStack.push_back(newState);

}

bool GameStateManager::isRunning()
{
    return _isRunning;
}
